package com.dnjn.happiness.biz.controller;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dnjn.happiness.biz.domain.Appraise;
import com.dnjn.happiness.biz.service.IAppraiseService;
import com.dnjn.happiness.common.core.constant.Constants;
import com.dnjn.happiness.common.core.constant.SecurityConstants;
import com.dnjn.happiness.common.core.domain.R;
import com.dnjn.happiness.common.core.model.ModelHappinessScores;
import com.dnjn.happiness.common.core.utils.StringUtils;
import com.dnjn.happiness.common.core.utils.bean.BeanUtils;
import com.dnjn.happiness.common.core.utils.poi.ExcelUtil;
import com.dnjn.happiness.common.cloud.controller.BaseController;
import com.dnjn.happiness.common.core.web.domain.AjaxResult;
import com.dnjn.happiness.common.log.annotation.Log;
import com.dnjn.happiness.common.log.enums.BusinessType;
import com.dnjn.happiness.common.security.annotation.RequiresPermissions;
import com.dnjn.happiness.common.security.utils.SecurityUtils;
import com.dnjn.happiness.common.security.utils.VerifyUtil;
import com.dnjn.happiness.system.api.RemoteDeptService;
import com.dnjn.happiness.system.api.RemoteUserService;
import com.dnjn.happiness.system.api.domain.SysDept;
import com.dnjn.happiness.system.api.domain.SysUser;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * appraiseController
 *
 * @author amber
 * @date 2023-10-20
 */
@Tag(name = "biz appraise appraise  评价", description = "appraise")
@RestController
@RequestMapping("/appraise")
public class AppraiseController extends BaseController {
    @Autowired
    private IAppraiseService appraiseService;


    @Autowired
    private RemoteDeptService deptService;

    @Autowired
    private RemoteUserService sysUserService;

    /**
     * 查询appraise列表
     */
    @RequiresPermissions("biz:appraise:list")
    @PostMapping("/list")
    @Log(title = "biz", businessType = BusinessType.LIST)
    public AjaxResult list(@RequestBody com.dnjn.happiness.biz.domain.vo.AppraiseSearchVO vo, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        Appraise appraise = new Appraise();
        BeanUtils.copyPropsIgnoreNull(vo, appraise);
        Page page = Page.of(current, size).addOrder(OrderItem.desc("appraise_id"));
        Page<Appraise> list = appraiseService.selectPageX(appraise, page);
        if (!CollectionUtils.isEmpty(list.getRecords())) {
            for (Appraise po : list.getRecords()) {
                Long fromUserDeptId = po.getFromUserDeptId();
                if (!ObjectUtils.isEmpty(fromUserDeptId)) {
                    R<SysDept> result = deptService.getInfoById(fromUserDeptId, SecurityConstants.INNER);
                    if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
                        po.setFromUserDeptName(result.getData().getDeptName());
                    }
                }
                Long userDeptId = po.getUserDeptId();
                if (!ObjectUtils.isEmpty(userDeptId)) {
                    R<SysDept> result = deptService.getInfoById(fromUserDeptId, SecurityConstants.INNER);
                    if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
                        po.setUserDeptName(result.getData().getDeptName());
                    }
                }
            }
        }
        return success(list);
    }

    @Operation(summary = "我的评价", description = " fromUserId 评价发起人,username评价人姓名")
    @PostMapping(value = "appraise/userId")
    @Log(title = "biz", businessType = BusinessType.SELECT)
    public AjaxResult getByFromUserId(@RequestBody com.dnjn.happiness.biz.domain.vo.AppraiseSearchVO domain, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {

        domain.setFromUserId(SecurityUtils.getUserId());
        if (Objects.isNull(domain.getDeptId())) {
            domain.setDeptId(SecurityUtils.getLoginUser().getDeptId());
        }
        Appraise appraise = new Appraise();
        BeanUtils.copyPropsIgnoreNull(domain, appraise);
        if (VerifyUtil.whetherAllPermissions()) {
            appraise.setWhetherAllPermissions(true);
        } else {
            appraise.setWhetherAllPermissions(false);
        }
        Page<Appraise> list = appraiseService.selectPageNew(appraise, Page.of(current, size).addOrder(OrderItem.desc("appraise_id")));

        return success(list);
    }

    @Operation(summary = " listGeRenInFoApr个人详情-评价", description = "需要沟通的(fromFront是true)-展示负面评价按时间顺序排序")
    @PostMapping("/PersonalAppraise")
    @Log(title = "biz", businessType = BusinessType.LIST)
    public AjaxResult listGeRenInFoApr(@RequestBody Appraise domain, @Parameter(required = true) @RequestParam(defaultValue = "false") Boolean fromFront, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
//        Assert.notNull(domain.getUserId(), "用户ID不能为空");
        if (fromFront) {
            domain.setEtype("NEGATIVE");//!
        }

        Page<Appraise> list = appraiseService.selectPageX(domain, Page.of(current, size).addOrder(OrderItem.desc("create_time")));
        return success(list);
    }

    /**
     * 导出appraise列表
     */
    @Log(title = "appraise", businessType = BusinessType.EXPORT)
    @RequiresPermissions("biz:appraise:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, Appraise appraise) {
        List<Appraise> list = appraiseService.list(Wrappers.query(appraise));
        ExcelUtil<Appraise> util = new ExcelUtil<Appraise>(Appraise.class);
        util.exportExcel(response, list, "appraise数据");
    }

    /**
     * 获取appraise详细信息
     */
    @RequiresPermissions("biz:appraise:query")
    @GetMapping(value = "/{appraiseId}")
    @Log(title = "biz", businessType = BusinessType.SELECT)
    public AjaxResult get(@PathVariable("appraiseId") Long appraiseId) {
        return success(appraiseService.getById(appraiseId));
    }

    /**
     * 新增appraise
     */
    @Operation(summary = "小程序-评价-新增评价")
    @Log(title = "appraise", businessType = BusinessType.INSERT)
    //@RequiresPermissions("biz:appraise:add")
    @PostMapping(value = {"/addAppraise", "add"})
    public AjaxResult add(@RequestBody Appraise appraise) {
        if (Objects.isNull(appraise.getIsAnonymous())) {
            appraise.setIsAnonymous('N');
        }
        Assert.notNull(appraise.getUserId(), "被评价者ID不能为空");
        Assert.notNull(appraise.getIsAnonymous(), "是否匿名不能为空");
        Assert.notNull(appraise.getXrefList(), "评价维度不能为空");
        appraise.setCreateBy(SecurityUtils.getUsername());
        SysUser user = SecurityUtils.getLoginUser().getUser();//获取当前登录用户作为发起者
        appraise.setFromUserId(user.getUserId());
        appraise.setAppraiseType("COMMON");
        appraise.setDeleted(Constants.UNDELETED);
        boolean yes = appraiseService.addAppraiseNew(appraise);
        return toAjax(yes);
    }

    /**
     * 修改appraise
     */
    @Log(title = "appraise", businessType = BusinessType.UPDATE)
    @RequiresPermissions("biz:appraise:edit")
    @PutMapping
    public AjaxResult edit(@RequestBody Appraise appraise) {
        return toAjax(appraiseService.updateById(appraise));
    }

    /**
     * 删除appraise
     */
    @Log(title = "appraise", businessType = BusinessType.DELETE)
    @RequiresPermissions("biz:appraise:remove")
    @DeleteMapping("/{appraiseIds}")
    public AjaxResult remove(@PathVariable Long[] appraiseIds) {
        boolean flag = appraiseService.lambdaUpdate().set(Appraise::getDeleted, Constants.DELETED)
                .in(Appraise::getAppraiseId, appraiseIds)
                .update();
        return toAjax(flag);
    }


    /**
     * 获取评价记录消极记录数-积极记录数
     */
    @Operation(summary = "获取评价记录消极记录数-积极记录数")
    @GetMapping("/getAppraiseTotal/{userId}")
    @Log(title = "biz", businessType = BusinessType.SELECT)
    public AjaxResult getAppraiseTotal(@PathVariable Long userId) {
        Assert.notNull(userId, "用户ID不能为空");
        List<ModelHappinessScores> list = appraiseService.getAppraiseHappinessScores(userId, "biz_appraise");
        return AjaxResult.success(list);
    }


    /**
     * 统计当日新增评价数量
     */
    @GetMapping("/todayAppraiseTotal")
    public AjaxResult todayAppraiseTotal() {
        Appraise appraise = new Appraise();
        appraise.setCurrDate(LocalDate.now());
        Page page = Page.of(1, 10).addOrder(OrderItem.desc("appraise_id"));
        Page<Appraise> page1 = appraiseService.selectPageX(appraise, page);
        return AjaxResult.success(page1.getTotal());
    }

    /**
     * 查询appraise列表-改版
     */
    @Operation(summary = " getlist   查询appraise列表-改版")
    @PostMapping("/getlist")
    @Log(title = "biz", businessType = BusinessType.SELECT)
    public AjaxResult getlist(@RequestBody com.dnjn.happiness.biz.domain.vo.AppraiseSearchVO vo, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        Appraise appraise = new Appraise();
        BeanUtils.copyPropsIgnoreNull(vo, appraise);
        Page page = Page.of(current, size).addOrder(OrderItem.desc("appraise_id"));
        if (VerifyUtil.whetherAllPermissions()) {
            appraise.setWhetherAllPermissions(true);
        } else {
            appraise.setWhetherAllPermissions(false);
        }
        Page<Appraise> list = appraiseService.selectPageNew(appraise, page);

        return success(list);

    }

    @Operation(summary = "getUserlist 人员列表", description = "{\n" +
            " \n" +
            "  \"sysUser\": {\n" +
            "    \n" +
            "    \"nickName\": \"许\"\n" +
            "   \n" +
            "  }\n" +
            "}")
    @PostMapping("/getUserlist")
    @Log(title = "biz", businessType = BusinessType.SELECT)
    public AjaxResult getUserlist(@RequestBody Appraise appraise) {
//        Appraise appraise = new Appraise();
//        BeanUtils.copyPropsIgnoreNull(vo, appraise);

        List<SysUser> list = new ArrayList<>();
        R<List<SysUser>> result = sysUserService.selectUserList(appraise.getSysUser(), SecurityConstants.INNER);
        if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())){
            list = result.getData();
        }

        return success(list);
    }

    @Data
    public static class AppraiseSearchVO implements Serializable {
        private Long userId;
        private Long fromUserId;
        private String etype;
        private Long fromUserDeptId;
        private Long userDeptId;
        private LocalDate currDate;
    }
}
